package me.twoday.library.mine.handler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.twoday.library.mine.R;
import me.twoday.library.mine.adapter.SettingListAdapter;
import me.twoday.library.mine.adapter.SettingListAdapter.Tagging;
import me.twoday.library.mine.common.LanguageUtil;
import me.twoday.library.mine.common.MessageUtil;
import me.twoday.library.mine.component.SettingListView;
import me.twoday.library.mine.domain.SettingInfo;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.SimpleAdapter;

/**
 * setting.xml에서 정의된 setting 값을 처리하는 헨들러  
 * 
 * @author 김학성
 * @since 2012. 4. 18.
 */
@SuppressWarnings("unused")
public class SettingHandler 
{
	private static final String TAG = "SettingHandler";
	private Activity mParentActivity;
	private SettingInfo mSettingInfo;
	private SettingListAdapter mListAdapter;
	private SettingListView mListView;
	
	public static final String ITEM_NAME = "title";
	public static final String ITEM_NUMBER = "detail";
	public static final int SETTING_LIST_SUPER_ROW = R.layout.setting_list_super_row;
	public static final int SETTING_LIST_SUB_ROW = R.layout.setting_list_sub_row;
	public static final int SETTING_LIST_SUB_ROW_TV_TITLE = R.id.setting_list_sub_row_tv_title;
	public static final int SETTING_LIST_SUB_ROW_TV_DETAIL = R.id.setting_list_sub_row_tv_detail;
	
	public static final int FIRST_SUPER_TITLE = 0;
	public static final int SECOND_SUPER_TITLE = 1;
	public static final int THIRD_SUPER_TITLE = 2;
	public static final int FOURTH_SUPER_TITLE = 3;
	public static final int FIRST_SUB_TITLE = 1;
	public static final int SECOND_SUB_TITLE = 2;
	public static final int THIRD_SUB_TITLE = 3;
	public static final int FOURTH_SUB_TITLE = 4;
	
	public SettingHandler(Activity activity)
	{
		mParentActivity = activity;
		mSettingInfo = new SettingInfo();
		createSettingData();
	}
	
	/**
	 * 엑티비티 반환 
	 *
	 * @return Activity
	 */
	public Activity getActivity()
	{
		return mParentActivity;
	}
	
	/**
	 * setting.xml 파일을 로드합니다. 
	 *
	 * @return
	 */
	public XmlPullParser loadSettingInfoFromXml()
	{
		XmlPullParser parser = null;
		switch (LanguageUtil.selectLanguage()) 
		{
			case LanguageUtil.KO:
				parser = mParentActivity.getResources().getXml(R.xml.setting_ko);
				break;
			case LanguageUtil.EN:
				parser = mParentActivity.getResources().getXml(R.xml.setting_en);
				break;
			case LanguageUtil.CH:
				parser = mParentActivity.getResources().getXml(R.xml.setting_ch);
				break;
			case LanguageUtil.JP:
				parser = mParentActivity.getResources().getXml(R.xml.setting_jp);
				break;
			default:
				Log.e(TAG, "XML 파일을 로드하는데 실패하였습니다.");
				break;
		}
		return parser;
	}
	
	/**
	 * 리스트를 표현하는데 사용되는 어댑터 객체를 설정하고
	 * 어뎁터에 값을 셋팅한다.
	 *
	 * @param listAdapter
	 */
	public void setListAdapter(SettingListAdapter listAdapter)
	{
		this.mListAdapter = listAdapter;
		pushSettingListIntoAdapter();
	}
	
	/**
	 * adapter 에 xml에서 불러온 값을 추가
	 *
	 */
	private void pushSettingListIntoAdapter() 
	{
		int listSize = mSettingInfo.settingListSize();
		ArrayList<List<Map<String,?>>> settingList = mSettingInfo.getSettingList();
		ArrayList<String> superTitles = mSettingInfo.getSuperTitleList();
	    for(int position=0;position<listSize;position++)
        {
	    	String superTitle = superTitles.get(position);
        	//FoodType foodType = mFoodTypeList.get(position);
        	SimpleAdapter simpleAdapter = new SimpleAdapter(mParentActivity, settingList.get(position),
        			SETTING_LIST_SUB_ROW, new String[]{ITEM_NAME,ITEM_NUMBER},
        			new int[]{SETTING_LIST_SUB_ROW_TV_TITLE,SETTING_LIST_SUB_ROW_TV_DETAIL});
        	mListAdapter.addSection(superTitle, simpleAdapter);
        }
	}

	/**
	 * 리스트를 표현하는데 사용되는 리스트뷰 객체를 설정한다.
	 *
	 * @param listView
	 */
	public void setListView(SettingListView listView)
	{
		this.mListView = listView;
	}
	
	/**
	 * 로드된 setting 정보를 셋팅합니다. 
	 *
	 */
	public void createSettingData()
	{
		XmlPullParser parser = loadSettingInfoFromXml();
		
		try {
			while(parser.getEventType() != XmlPullParser.END_DOCUMENT)
			{
				try {
					if(parser.getEventType() == XmlPullParser.START_TAG)
					{
						if(parser.getName().equals("super_title"))
						{
							mSettingInfo.addSuperTitle(parser.getAttributeValue(0));
							mSettingInfo.createNewSubRows();
						}
						else if(parser.getName().equals("sub_title"))
						{
							mSettingInfo.addSubTitleToRow(parser.getAttributeValue(0));
						}
						else if(parser.getName().equals("sub_detail"))
						{
							mSettingInfo.addSubDetailToRow(parser.getAttributeValue(0));
						}
					}
					else if(parser.getEventType() == XmlPullParser.END_TAG)
					{
						if(parser.getName().equals("super_title"))
						{
							mSettingInfo.addSubRowsToSettingList();
						}
					}
				} 
				catch (XmlPullParserException e) 
				{
					Log.e(TAG, e.getMessage());
					e.printStackTrace();
				}
				try {
					parser.next();
				} catch (IOException e) 
				{
					Log.e(TAG, e.getMessage());
					e.printStackTrace();
				}
				
			}
		} 
		catch (XmlPullParserException e) 
		{
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * ListView에서 클릭이벤트를 handler로 빼서 관리
	 * 직관적으로 클릭이벤트 처리위해 아래와 같은 if else 구문으로 처
	 *
	 * @param view (클릭된뷰)
	 */
	public void onRowClick(View v) 
	{
		Tagging tagging = (Tagging)v.getTag();
		String superTitle = tagging.superTitle;
		int selectSubTitleIndex = tagging.subTitleIndex;
		int superTitleListSize = mSettingInfo.superTitleListSize();
		ArrayList<String> superTitleList = mSettingInfo.getSuperTitleList();
		int selectSuperTitleIndex = -1;
		
		for(int position = 0; position < superTitleListSize; position++)
		{
			if(superTitleList.get(position).equals(superTitle))
			{
				selectSuperTitleIndex = position;
				break;
			}
		}
		
		
		// 국제화를 위해서 어쩔수 없이 다음과 같은 이벤트 처리를 선택하였습니다.
		// 각각에 대해서 처음 설정시 주석을 철저히 달아 놓습니다.
		
		// 인 증 
		if(selectSuperTitleIndex == FIRST_SUPER_TITLE)
		{
			// 광운대 학생인증 정보 입력 
			if(selectSubTitleIndex == FIRST_SUB_TITLE)
			{
				MessageUtil.toast(mParentActivity, "인증성공");
			}
			/*
			else if(selectSubTitleIndex == SECOND_SUB_TITLE)
			{
				
			}
			else if(selectSubTitleIndex == THIRD_SUB_TITLE)
			{
				
			}
			else if(selectSubTitleIndex == FOURTH_SUB_TITLE)
			{
				
			}
			*/
			else
			{
				Log.e(TAG, "정의되있지 않은 이벤트 입니다1.");
			}
		}
		// 어플리케이션 정보 
		else if(selectSuperTitleIndex == SECOND_SUPER_TITLE)
		{
			// 버전 정보 
			if(selectSubTitleIndex == FIRST_SUB_TITLE)
			{
				MessageUtil.alert(mParentActivity, "KwangWoonUniv App 1.0.0");
			}
			// 피드백 보내기 
			else if(selectSubTitleIndex == SECOND_SUB_TITLE)
			{
				MessageUtil.toast(mParentActivity, "피드백 보냄!");
			}
			/*
			else if(selectSubTitleIndex == THIRD_SUB_TITLE)
			{
				
			}
			else if(selectSubTitleIndex == FOURTH_SUB_TITLE)
			{
				
			}
			*/
			else
			{
				Log.e(TAG, "정의되있지 않은 이벤트 입니다.2");
			}
		}
		// 제작자 정보
		/*
		else if(selectSuperTitleIndex == THIRD_SUPER_TITLE)
		{
			
			if(selectSubTitleIndex == FIRST_SUB_TITLE)
			{
				
			}
			else if(selectSubTitleIndex == SECOND_SUB_TITLE)
			{
				
			}
			else if(selectSubTitleIndex == THIRD_SUB_TITLE)
			{
				
			}
			else if(selectSubTitleIndex == FOURTH_SUB_TITLE)
			{
				
			}
			else
			{
				Log.e(TAG, "정의되있지 않은 이벤트 입니다.");
			}
		}
		*/
		/* 정의 되있지 않은 설정으로 주석처리 해놓습니다.
		 * 필요할 경우 주석을 풀고 사용합니다.
		else if(selectSuperTitleIndex == FOURTH_SUPER_TITLE)
		{
			if(selectSubTitleIndex == FIRST_SUB_TITLE)
			{
				
			}
			else if(selectSubTitleIndex == SECOND_SUB_TITLE)
			{
				
			}
			else if(selectSubTitleIndex == THIRD_SUB_TITLE)
			{
				
			}
			else if(selectSubTitleIndex == FOURTH_SUB_TITLE)
			{
				
			}
			else
			{
				Log.e(TAG, "정의되있지 않은 이벤트 입니다.");
			}
		}
		*/
		else
		{
			Log.e(TAG, "SuperTitle을 찾을수 없습니다.");
		}
	}
}
